import functools
from flask import request, jsonify, current_app, session
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired, BadSignature

from models.user import User


# 创建token
def create_token(user_id, secret_key, expires_in=3600):
    s = Serializer(secret_key, expires_in=expires_in)       # 传入私钥和过期时间
    token = s.dumps({"user_id": user_id}).decode("ascii")        # 接收用户id转换与编码
    return token


# 验证token
def verify_token(token, secret_key):
    s = Serializer(secret_key)
    try:
        token_data = s.loads(token).get("user_id")
        return token_data.get("user_id")
    except SignatureExpired:
        print("token已过期")
        return None
    except BadSignature:
        print("token错误")
        return None


def login_required(view_func):
    @functools.wraps(view_func)
    def token_verify(*args, **kwargs):
        try:
            token = session.get("token")
            if token:
                user_id = verify_token(token, current_app.config["SECRET_KEY"])
                if user_id:
                    return view_func(*args, **kwargs)
                else:
                    return jsonify(code=2, msg="token无效")
            else:
                return jsonify(code=2, msg="缺少参数token")
        except Exception:
            return jsonify(code=3, msg='缺少参数token')

    return token_verify


def get_user(token):
    user_id = verify_token(token, current_app.config["SECRET_KEY"])

    if user_id:
        return User.query.filter(User.id == user_id).first()
    else:
        return None
